﻿function LoginFactory($http, $q) {
    var isLoggedIn = false;

    var checkLogin = function () {
        if (localStorage.getItem('token')) return isLoggedIn = true;
        return isLoggedIn = false;
    }
    var Login = function (user) {
        var deferred = $q.defer();
        $http({
            url: '/Token',
            method: 'POST',
            contentType: 'application/x-www-form-urlencoded',
            data: 'username=' + user.username + '&password=' + user.password + '&grant_type=password'
        }).success(function (data) {
            localStorage.setItem('token', data.access_token);
            isLoggedIn = true;
            deferred.resolve();
        }).error(function (data) {
            localStorage.removeItem('token');
            isLoggedIn = false;
            deferred.reject();
        });
        return deferred.promise;
    }

    var Logout = function () {
        localStorage.removeItem('token');
        isLoggedIn = false;
    }

    checkLogin();

    return {
        Login: Login,
        Logout: Logout,
        isLoggedIn: isLoggedIn,
        checkLogin: checkLogin
    }
}
LoginFactory.$inject = ['$http', '$q'];